package com.ecloud.common.data.exception;

import java.text.MessageFormat;

/**
 * 自定义异常
 *
 * @author LiuGangQiang Create in 2020/10/21
 */
public class DynamicDataSourceException extends RuntimeException {

    private static final long serialVersionUID = -2164455726135135128L;
    /**
     * 错误消息
     *
     * @author LiuGangQiang Create in 2021/03/21
     */
    private String msg;
    /**
     * 参数
     *
     * @author LiuGangQiang Create in 2021/03/21
     */
    private Object[] args;

    /**
     * @author LiuGangQiang Create in 2021/03/21
     */
    public DynamicDataSourceException() {
        super();
    }

    /**
     * @author LiuGangQiang Create in 2021/03/21
     * @param msg 错误消息
     */
    public DynamicDataSourceException(String msg) {
        super(msg);
        this.msg = msg;
    }

    /**
     *
     * @author LiuGangQiang Create in 2021/03/21
     * @param msg  错误消息（注意使用{index}从0开始）
     * @param args 占位参数
     */
    public DynamicDataSourceException(String msg, Object... args) {
        super();
        this.msg = msg;
        this.args = args;
    }

    @Override
    public String getMessage() {
        if (isBlank(getMsg()) && args != null && args.length > 0) {
            return MessageFormat.format(msg, args);
        }
        /* 如果不传参数，直接调用父类方法 */
        return super.getMessage();
    }

    /**
     * @return the msg
     */
    public String getMsg() {
        return msg;
    }

    /**
     * @param msg the msg to set
     */
    public void setMsg(String msg) {
        this.msg = msg;
    }

    /**
     * @return the args
     */
    public Object[] getArgs() {
        return args;
    }

    /**
     * @param args the args to set
     */
    public void setArgs(Object[] args) {
        this.args = args;
    }

    private boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }
}
